package middleware

import (
	"github.com/gin-gonic/gin"
	"jihe.common/protos/admin_auth_server"
	"jihe.common/protos/admin_auth_server/proto"
	"jihe.common/resp"
	"net/http"
	"strings"
)

func VerifyToken() gin.HandlerFunc {
	return func(c *gin.Context) {
		//if conf.Get().Runmode == "debug" {
		//	c.Next()
		//	return
		//}
		token := c.GetHeader("Authorization")
		uid := c.GetHeader("Uid")
		_, err := admin_auth_server.AdminAuthVerifyToken(c, &proto.AdminAuthVerifyTokenReq{
			Uid:   uid,
			Token: token,
		})
		if err != nil {
			if strings.Index(err.Error(), "errorno=01") != -1 {
				resp.RespCode(c, http.StatusUnauthorized, "账号状态已发生变化，请重新登录")
				c.Abort()
				return
			}
			if strings.Index(err.Error(), "errorno=02") != -1 {
				resp.RespCode(c, http.StatusUnauthorized, "账号已在别处登录")
				c.Abort()
				return
			}
			if strings.Index(err.Error(), "errorno=03") != -1 {
				resp.RespCode(c, http.StatusUnauthorized, "登录已过期")
				c.Abort()
				return
			}
			if strings.Index(err.Error(), "errorno=04") != -1 {
				resp.RespCode(c, http.StatusUnauthorized, "未授权")
				c.Abort()
				return
			}
		}
		c.Set("uid", uid)
		c.Next()
	}
}
